﻿using NewsSystem.ClientModels;
using NewsSystem.Contracts;
using NewsSystem.Models;
using NewsSystem.WebApi.Models;
using System;
using System.Net.Http;
using System.Web.Http;

namespace NewsSystem.WebApi.Controllers
{
    public class UsersController : BaseController
    {
        public const int ExpireTime = 15;

        public UsersController(INewsUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        [HttpPost]
        [ActionName("loginaa")]
        public HttpResponseMessage LoginUser(LoginUserModel userModel)
        {
            var responseMsg = this.PerformOperation<UserLoggedModel>(() =>
            {
                //TODO: ModelState.IsValid
                var user = this.Uow.User.GetByEmailAndPassword(userModel.Email, userModel.Password);
                if (user == null)
                {
                    throw new ServerErrorException();
                }

                user.SessionId = this.GetSessionId();
                user.ExpireDate = DateTime.Now.AddMinutes(ExpireTime);
                this.Uow.Commit();

                return new UserLoggedModel()
                {
                    Email = user.Email,
                    SessionKey = user.SessionId
                };
            });

            return responseMsg;
        }

        [HttpPost]
        [ActionName("registeraa")]
        public HttpResponseMessage RegisterUser(RegisterUserModel userModel)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                //TODO: ModelState.IsValid
                var user = new User();
                user.Email = userModel.Email;
                user.PasswordHashed = userModel.Password;
                user.NickName = userModel.NickName;
                user.SessionId = this.GetSessionId();
                user.ExpireDate = DateTime.Now.AddMinutes(ExpireTime);

                this.Uow.User.Add(user);
            });

            return responseMsg;
        }

        private string GetSessionId()
        {
            return Guid.NewGuid().ToString();
        }
    }
}
